package com.tl.mqtt.mqtt;

import org.eclipse.paho.client.mqttv3.*;
import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
public class MqttPushClient implements InitializingBean {

    private Logger logger = LoggerFactory.getLogger(MqttPushClient.class);
    @Autowired
    private MqttConfig config;
    private MqttClient client;

    @Override
    public void afterPropertiesSet() throws Exception {
        logger.info("MQTT建立链接");
        this.connect();
    }

    public void connect(){
        try {
            client = new MqttClient(config.getUrl(),config.getClientId()
                    ,new MemoryPersistence());
            MqttConnectOptions options = new MqttConnectOptions();
            options.setCleanSession(false);
            options.setUserName(config.getUsername());
            options.setPassword(config.getPassword().toCharArray());
            options.setConnectionTimeout(60000);
            options.setKeepAliveInterval(30);
            options.setMaxInflight(1000);
            options.setAutomaticReconnect(true);
            String topic = config.getTopic();
            int qos = 1;
            client.setTimeToWait(30000L);
            client.setCallback(new MessageCallback(client,options,topic,qos));
            logger.info("开始链接");
            client.connect(options);
            //logger.info("MQTT订阅主题:{},质量QOS:{}",topic,qos);
            //client.subscribe(topic,qos);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 消息发布
     * @param qos 0，1，2
     * @param topic 主题
     * @param publishMsg 内容
     */
    public void publish(int qos,String topic,String publishMsg){
        try {
            MqttMessage message = new MqttMessage();
            message.setQos(qos);
            message.setPayload(publishMsg.getBytes("UTF-8"));
            MqttTopic sendTopic = client.getTopic(topic);
            MqttDeliveryToken token = sendTopic.publish(message);
        } catch (Exception e) {
            e.printStackTrace();
            logger.info("发布异常信息：{}",e);
        }
    }

    /**
     * 订阅主题
     * @param topic 主题
     * @param qos 质量
     */
    public void subscribe(String topic,int qos){
        try {
            client.subscribe(topic,qos);
        } catch (MqttException e) {
            e.printStackTrace();
        }
    }

}
